package com.example.demo.leetcode.top100;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _14合并区间
 * @description
 * @date 2023/06/06 21:15
 * <p>
 * ******************************************************
 */
public class _14合并区间 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> {
            if (a[0] == b[0]) {
                return b[1] - a[1];
            }
            return a[0] - b[0];
        });

        LinkedList<LinkedList<Integer>> res = new LinkedList<>();
        LinkedList<Integer> first = new LinkedList<Integer>(){{
            add(intervals[0][0]);
            add(intervals[0][1]);
        }};
        res.add(first);

        for (int i = 1; i < intervals.length; i++) {
            int[] curr = intervals[i];
            LinkedList<Integer> last = res.getLast();

            if (last.getLast() >= curr[0]) {
                if (last.getLast() < curr[1]) {
                    last.removeLast();
                    last.add(curr[1]);
                }
            } else {
                LinkedList<Integer> list = new LinkedList<Integer>(){{
                    add(curr[0]);
                    add(curr[1]);
                }};
                res.add(list);
            }

        }

        int[][] result = new int[res.size()][2];
        for (int i = 0; i < res.size(); i++) {
            LinkedList<Integer> curr = res.get(i);
            result[i] = curr.stream().mapToInt(Integer::intValue).toArray();
        }
        return result;
    }
}
